package com.ccp.dev.workflow.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.workflow.model.ActDefModel;
import com.ccp.dev.workflow.service.ActDefModelService;
import com.ccp.dev.workflow.service.BpmnXmlService;
import org.flowable.ui.common.service.exception.BadRequestException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

/**
 * ClassDescribe:
 * 流程xml文件生成控制类
 * @author :wangcheng
 * Date: 2019-06-05
 */
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_WORKFLOW + "/bpmnXml")
@Controller
@Action(ownermodel = SysAuditModelType.PROCESS_MANAGEMENT)
public class BpmnXmlController extends SysBaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(BpmnXmlController.class);

    @Resource
    private ActDefModelService actDefModelService;
    @Resource
    private BpmnXmlService bpmnXmlService;

    /**
     * 下载xml文件
     * @param response http响应
     * @param processModelId 模型id
     */
    @RequestMapping(value = "/bpmn20/download", method = RequestMethod.GET)
    @Action(description = "下载流程xml文件", detail = "下载流程xml文件")
    public ResultData getProcessModelBpmn20Xml(HttpServletResponse response, @RequestParam String processModelId) {
        if (processModelId == null) {
            return getResultDataError("model.not.exist");
        }

        try {
            ActDefModel model = actDefModelService.getOneById(processModelId);
            bpmnXmlService.generateBpmn20Xml(response, model);
            return getResultDataSuccess("xmlFile.generate.success");
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return getResultDataError("xmlFile.generate.failure");
        }
    }

    /**
     * 显示xml文件
     * @param modelId 流程模型id
     */
    @RequestMapping(value = "/bpmn20", method = RequestMethod.GET)
    @Action(description = "显示流程xml文件", detail = "显示流程xml文件")
    public String getProcessModelBpmn20Xml(Model model, @RequestParam String modelId) {
        ActDefModel actModel = actDefModelService.getOneById(modelId);
        if (model == null) {
            throw new BadRequestException("模型不存在");
        }
        String bpmn20Xml = bpmnXmlService.generateBpmn20Xml(actModel);
        model.addAttribute("bpmn20Xml", bpmn20Xml);
        return "workflow/actDefModel/bpmnXml";
    }


}
